﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace RayDen.Library.Entity
{
    public class DependencyContainer
    {
        private Dictionary<Type, object> cache;
        private Dictionary<Type, Func<object, object>> actionCache;



        public DependencyContainer()
        {
            cache = new Dictionary<Type, object>();
            actionCache = new Dictionary<Type, Func<object, object>>();
        }

        public void Populate(params object[] dependencies)
        {
            foreach (var dependency in dependencies)
            {
                if (!this.cache.ContainsKey(dependency.GetType()))
                    this.cache.Add(dependency.GetType(), dependency);
            }
        }

        public void Populate(params Func<object,object>[] creators )
        {
            
        }

        public TDependency Get<TDependency>()
        {
            try
            {
                return (TDependency) cache[typeof (TDependency)];
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Couldnt resolve dependency ",ex);
            }
        }

        public TDependency Get<TDependency>(string actionName)
        {
            var dp = Check(typeof (TDependency));
            if ( dp != null 
                &&
                dp.GetType()
                  .GetCustomAttributes(typeof (EntityActionAttribute), false)
                  .Cast<EntityActionAttribute>()
                  .Any(item => item.ActionName.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)))
                return (TDependency)dp;
            throw new ApplicationException("Couldnt resolve dependency "+actionName);
        }


        private object Check(Type val)
        {
            if (cache.ContainsKey(val))
                return cache[val];
            return (from o_c in cache where val.IsInstanceOfType(o_c.Value) select o_c.Value).FirstOrDefault();
        }
    }
}
